package day07.service.impl;

import day07.dao.UserDao;
import day07.dao.impl.UserDaoImpl;
import day07.entity.User;
import day07.service.UserService;
import day07.utils.JDBCUtils;

import java.sql.Connection;
import java.util.List;

public class UserServiceImpl implements UserService {
    UserDao userDao = new UserDaoImpl();

    @Override
    public int save(User user) {
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        return userDao.save(connection, "insert into user values(?,?,?,?)", user.getId(), user.getName(), user.getPassword(), user.getAddress());
    }

    @Override
    public int update(User user) {
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        // 校验参数，先通过ID回显用户
        User userById = userDao.queryById(connection, "select * from user where id = ?", User.class, user.getId());
        if (userById == null) {
            throw new RuntimeException("用户不存在");
        }
        Long id = user.getId();
        String name = user.getName();
        String password = user.getPassword();
        String address = user.getAddress();
        if (name != null) {
            userById.setName(name);
        }
        if (password != null) {
            userById.setPassword(password);
        }
        if (address != null) {
            userById.setAddress(address);
        }
        Connection connection2 = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        return userDao.update(connection2, "update user set name = ?, password = ?, address = ? where id = ?", userById.getName(), userById.getPassword(), userById.getAddress(), id);
    }

    @Override
    public int delete(User user) {
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        return userDao.delete(connection, "delete from user where id = ?", user.getId());
    }

    @Override
    public List<User> queryAll() {
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        return userDao.queryAll(connection, "select * from user");
    }

    @Override
    public User queryById(Long id) {
        Connection connection = JDBCUtils.getConnection("jdbc:mysql://localhost:3306/test2", "root", "mysql");
        return userDao.queryById(connection, "select * from user where id = ?", User.class, id);
    }
}
